<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\facade\Request;
class Novel extends Controller
{
    protected $middleware = ['VerifyLogin'];


    /*
     * 筛选条件获取 - 书籍搜索列表
     * */
    public function screen()
    {
        $freq = Db::table('novel_freq')->field('id,name')->order('id ASC')->select();
        $freq_id_gh = array_column($freq,'id');

        $category = Db::table('novel_class_mp_freq')->where('freq_id','in',$freq_id_gh)
                    ->field('freq_id,class_id')->select();

        $lang = input('lang','zh2cht');

        $cid_gh = array_column($category,'class_id');
        $cats = Db::table('novel_class')->where('id','in',$cid_gh)->order('wgt DESC,id DESC')->column('id,name,en_name');

        $category_new = [];
        foreach ($category as $k=>$v)
        {
            if(isset($cats[$v['class_id']]))
            {
                $category_new[] = [
                    'name' => $lang == 'en' ? $cats[$v['class_id']]['en_name'] : $cats[$v['class_id']]['name'],
                    'class_id' => $v['class_id'],
                    'freq_id' => $v['freq_id']
                ];
            }

        }


        if($lang == 'en')
        {
            $category_freq = [
                1 => [ 0 => ['name' => 'All', 'field' => 'freq_id', 'value'=>1] ],
                2 => [ 0 => ['name' => 'All', 'field' => 'freq_id', 'value'=>2] ]
            ];
        }else{
            $category_freq = [
                1 => [ 0 => ['name' => '全部', 'field' => 'freq_id', 'value'=>1] ],
                2 => [ 0 => ['name' => '全部', 'field' => 'freq_id', 'value'=>2] ]
            ];
        }


        foreach ($category_new as $v)
        {
            $category_freq[$v['freq_id']][] = [
                'name' => $v['name'], 'field' => 'class_id', 'value' => $v['class_id']
            ];
        }


        if($lang == 'en')
        {
            $data[0][] = ['name'=>'For Men','field'=>'freq_id','value'=>1];
        }else{
            $data[0][] = ['name'=>'男生','field'=>'freq_id','value'=>1];
        }

        $data[0][] = $category_freq[1];
        if($lang == 'en')
        {
            $data[0][] = [
                0 => ['name'=>'All','field'=>'update_status','value'=>''],
                1 => ['name'=>'Serialize','field'=>'update_status','value'=>'0'],
                2 => ['name'=>'Completed','field'=>'update_status','value'=>'1']
            ];
        }else{
            $data[0][] = [
                0 => ['name'=>'全部','field'=>'update_status','value'=>''],
                1 => ['name'=>'連載','field'=>'update_status','value'=>'0'],
                2 => ['name'=>'完結','field'=>'update_status','value'=>'1']
            ];
        }

        if($lang == 'en')
        {
            $data[1][] = ['name'=>'For Women','field'=>'freq_id','value'=>2];
        }else{
            $data[1][] = ['name'=>'女生','field'=>'freq_id','value'=>2];
        }

        $data[1][] = $category_freq[2];

        if($lang == 'en')
        {
            $data[1][] = [
                0 => ['name'=>'All','field'=>'update_status','value'=>''],
                1 => ['name'=>'Serialize','field'=>'update_status','value'=>'0'],
                2 => ['name'=>'Completed','field'=>'update_status','value'=>'1']
            ];
        }else{
            $data[1][] = [
                0 => ['name'=>'全部','field'=>'update_status','value'=>''],
                1 => ['name'=>'連載','field'=>'update_status','value'=>'0'],
                2 => ['name'=>'完結','field'=>'update_status','value'=>'1']
            ];
        }


        return json(['code'=>0,'msg'=>'success','data'=>$data]);
    }

    /*
     * 书籍搜索列表
     * */
    public function search()
    {
        $params = Request::param('', '', 'strip_tags,trim');
		$params['lang'] = input('lang','zh2cht');

        $NovelLogic = \think\facade\App::model('Novel', 'logic');
        $result = $NovelLogic->getSearchList($params);

        if($result)
        {
			foreach($result['list'] as $k=>$v)
			{
				if($params['lang'] == 'en')
				{
					$result['list'][$k]['update_status'] = $v['update_status'] == '連載中' ? 'Serialize' : 'Completed';
				}
				
			}
            return json(['code'=>0,'msg'=>'success','data'=>$result]);
        }

        return json(['code'=>102,'msg'=>'数据为空','data'=>[]]);
    }

    /*
     * 书籍详情页面
     * */
    public function detail()
    {
        $params = Request::param('', '', 'strip_tags,trim');
        $verify_result = $this->validate($params, 'Novel.detail');

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }

        $NovelLogic = \think\facade\App::model('Novel', 'logic');
        $bookInfo = $NovelLogic->getInfo($params);

        if($bookInfo)
        {
            $relatedBooks = $NovelLogic->getRelatedBooks($params['nid']);

            return json(['code'=>0,'msg'=>'success','data'=>[
                'bookInfo' => $bookInfo, 'relatedBooks' => $relatedBooks
            ]]);
        }

        return json(['code'=>102,'msg'=>'数据为空','data'=>[]]);
    }

    /*
     * 章节目录
     * */
    public function catalogue()
    {
        $params = Request::param('', '', 'strip_tags,trim');
        $verify_result = $this->validate($params, 'Novel.detail');

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }

        $ChapterLogic = \think\facade\App::model('Chapter', 'logic');
        $result = $ChapterLogic->getList($params);

        if($result)
        {
            return json(['code'=>0,'msg'=>'success','data'=>$result]);
        }

        return json(['code'=>102,'msg'=>'数据为空','data'=>[]]);
    }

    /*
     * 章节内容
     * */
    public function content()
    {
        $params = Request::param('', '', 'strip_tags,trim');
        $verify_result = $this->validate($params, 'Novel.content');

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }

        $checkIpBlackResult = checkIpBlackByToken();
        if($checkIpBlackResult['status'] == true)
        {
            $params['nid'] = $checkIpBlackResult['link_replace_nid'] >= 1 ? $checkIpBlackResult['link_replace_nid'] : $params['nid'];
        }

        if( !(isset($params['chapter_no']) && $params['chapter_no'] >= 1) )
        {
            $bookshelf = Db::table('quick_user_bookshelf')->where('uid',request()->userInfo['id'])
                        ->where('novel_id',$params['nid'])->field('chapter_no')
                        ->order('read_time DESC')->findOrEmpty();

            if($bookshelf)
            {
                $params['chapter_no'] = $bookshelf['chapter_no'];
            }else{
                $params['chapter_no'] = 1;
            }
        }

        $bookInfo = Db::table('novel')->where('id',$params['nid'])
                    ->where('in_shelf',1)->field('id,words_fee,origin_title')->findOrEmpty();

        if(empty($bookInfo))
        {
            return json(['code'=>102,'msg'=>'书籍不存在','data'=>[]]);
        }

        $ChapterLogic = \think\facade\App::model('Chapter', 'logic');
        $chapterInfo = $ChapterLogic->getInfo($params);

        if(empty($chapterInfo))
        {
            return json(['code'=>102,'msg'=>'数据为空','data'=>[]]);
        }

        $multiple = sprintf("%.1f", $chapterInfo['word_count'] / 1000);
        $chapterInfo['spend_ficoin'] = intval($multiple * $bookInfo['words_fee']);

        //阅读扣币
        $UserLogic = \think\facade\App::model('User', 'logic');
        $resultCost = $UserLogic->readCost($chapterInfo,$params);

        //余额不足跳转充值页面
        if($resultCost['code'] == 12){

            $encrypt_data              = txtEncrypt(mb_substr($chapterInfo['content'], 0, 30) . "……");
            $chapterInfo['content']    = $encrypt_data['encryptedData'];
            $chapterInfo['iv']         = $encrypt_data['iv'];

            return json([ 'code'=>105, 'msg'=>$resultCost['msg'], 'data'=>[
                'chapter_no'=>$params['chapter_no'],'chapter_title'=>$chapterInfo['chapter_title'],
                'bookname'=>$bookInfo['origin_title'],'content'=>$chapterInfo['content'],
                'iv'=>$chapterInfo['iv'],'prev_chapter_no'=>$chapterInfo['prev_chapter_no'],
                'next_chapter_no'=>$chapterInfo['next_chapter_no'],'word_count'=>$chapterInfo['word_count'],
                'is_pay'=>$chapterInfo['is_pay']
            ]]);
        }

        if($resultCost['code'] > 0){
            return json(['code'=>$resultCost['code'],'msg'=>$resultCost['msg'],'data'=>[]]);
        }

        $recordTable = "quick_user_read_record_" . date("Ym");
        $recordSave['uid']          = request()->userInfo['id'];
        $recordSave['novel_id']     = $params['nid'];
        $recordSave['chapter_no']   = $params['chapter_no'];
        $recordSave['pay_read']     = $resultCost['is_pay'];
        $recordSave['used_all']     = $resultCost['used_point']+$resultCost['used_coin'];
        $recordSave['used_point']   = $resultCost['used_point'];
        $recordSave['used_coin']    = $resultCost['used_coin'];
        $recordSave['channel_id']   = request()->channelId;
        $recordSave['agent_id']     = request()->agentId;
        $recordSave['read_date']    = date("Y-m-d");

        Db::table($recordTable)->insert($recordSave);


        if($resultCost['is_pay'] == 1)
        {
            Db::table('quick_user_consume_record')->insert(['uid'=>request()->userInfo['id'],'novel_id'=>$params['nid'],'chapter_no' => $params['chapter_no']]);
        }

        /**用户阅读记录*/
        $BookshelfLogic = \think\facade\App::model('Bookshelf', 'logic');
        $BookshelfLogic->refresh(request()->userInfo['id'], $params['nid'], $params['chapter_no']);

        $chapterInfo['bookname'] = $bookInfo['origin_title'];

        $encrypt_data              = txtEncrypt($chapterInfo['content']);
        $chapterInfo['content']    = $encrypt_data['encryptedData'];
        $chapterInfo['iv']         = $encrypt_data['iv'];

        return json(['code'=>0,'msg'=>'success','data'=>$chapterInfo]);
    }

}